/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { omitBy } from 'lodash';
import { useEffect, useMemo } from 'react';
import ReverseIconWidget from '../../../../../common/RJSFWidgets/ReverseIconWidget';
import {
  getMinimumCommonFields,
  getMinimumCommonParamsForCommand,
  initFormDataWithProps,
  minimumFormValidation,
} from './common-fields';
import { commonUiSchema } from './common-ui-schema';
import { ChildHoleProps, MinCommonFormData, MinCommonParams } from './types';

type FormData = {
  type?: string;
} & MinCommonFormData;

type Params = {
  type?: string;
} & MinCommonParams;

export function StraightHole({
  onClose,
  editDxid,
  props,
  formData,
  setFormData,
}: ChildHoleProps<Params, FormData>) {
  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      getMinimumCommonFields(formData),
      (val) => val == null,
    );
    return {
      type: 'object',
      properties,
    } as RJSFSchema;
  }, [formData.bottomType, formData.mode]);
  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useEffect(() => {
    if (props == null) {
      return;
    }

    const { params } = props;

    initFormDataWithProps(params, initEditDependency, picker).then(setFormData);
  }, [editDxid]);

  const isFormDataValid = () => {
    return minimumFormValidation(formData);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-holes', {
      commandName: 'CreateHoles',
      editDxid,
      dependencies: props?.shape ? [props.params.base] : [],
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    return confirmCommand(
      {
        a: {
          type: 'Simple',
          ...getMinimumCommonParamsForCommand(formData),
        } as Params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
    }),
    [formData],
  );

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      submitLoading={isLoading}
      formData={finalFormData}
      widgets={{
        reverseIcon: ReverseIconWidget,
      }}
      onChange={(v) => {
        setFormData(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={commonUiSchema}
      isFormDataValid={isFormDataValid()}
    />
  );
}
